<template>
  <div>
    <el-drawer
      size="650px"
      :visible.sync="drawer"
      direction="rtl"
      :show-close="false"
    >
      <div slot="title" class="title l-f l-row-sb">
        <div class="title_label">{{ isEdit ? "编辑" : "创建" }}分站超管</div>
        <div>
          <el-button @click="drawer = false" size="mini">取 消</el-button>
          <el-button @click="resetForm" size="mini">重 置</el-button>
          <el-button type="primary" @click="submitForm" size="mini"
            >{{ isEdit ? "保 存" : "创 建" }}</el-button
          >
        </div>
      </div>
      <div class="content" v-loading="loading">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="180px"
        >
          <el-form-item label="分站名称" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="分站超管账号" prop="account">
            <el-input
              v-model="ruleForm.account"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <template v-if="!isEdit">
            <el-form-item label="分站超管密码" prop="pwd">
              <el-input
                v-model="ruleForm.pwd"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.pwd"
              label="分站超管确认密码"
              prop="checkPwd"
            >
              <el-input
                v-model="ruleForm.checkPwd"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </template>
          <el-form-item label="分站超管姓名" prop="realName">
            <el-input
              v-model="ruleForm.realName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="ruleForm.phone"
              type="number"
              :maxlength="11"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="地区选择" prop="cityId">
            <el-cascader
              v-model="ruleForm.cityId"
              :options="cityList"
              :show-all-levels="false"
              clearable
              filterable
              :props="{
                checkStrictly: true,
                emitPath: false,
                value: 'cityId',
                label: 'name',
                children: 'child',
              }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="账号是否独立" prop="independent">
            <el-switch
              v-model="ruleForm.independent"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
          <template v-if="ruleForm.independent === 1">
            <!-- 小程序配置 -->
            <el-form-item label="AppID(小程序ID)" prop="routineAppid">
              <el-input
                v-model="ruleForm.routineAppid"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="AppSecret(小程序密钥)" prop="routineAppsecret">
              <el-input
                v-model="ruleForm.routineAppsecret"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
            <!-- 小程序支付配置 -->
            <el-form-item label="商户号" prop="payRoutineMchid">
              <el-input
                v-model="ruleForm.payRoutineMchid"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="支付证书" prop="payRoutineCertificatePath">
              <el-input
                v-model="ruleForm.payRoutineCertificatePath"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="支付秘钥" prop="payRoutineKey">
              <el-input
                v-model="ruleForm.payRoutineKey"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </template>
          <el-form-item label="是否开启" prop="status">
            <el-switch v-model="ruleForm.status"></el-switch>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { Debounce } from "@/utils/validate";
import { cityListTree } from "@/api/logistics.js";
import { postCity, putCity, getCityDetail } from "@/api/city";
export default {
  data() {
    return {
      isEdit: false,
      drawer: false,
      currentId: "",
      ruleForm: {
        account: "",
        pwd: "",
        checkPwd: "",
        cityId: "",
        independent: 0, // 账号是否独立 0：否 1：是
        name: "",
        phone: "",
        realName: "",
        status: true,
        routineAppid: "",
        routineAppsecret: "",
        payRoutineMchid: "",
        payRoutineCertificatePath: "",
        payRoutineKey: "",
      },
      rules: {
        account: [
          {
            required: true,
            message: "请输入分站账号",
            trigger: ["blur", "change"],
          },
        ],
        pwd: [
          {
            required: true,
            message: "请输入分站密码",
            trigger: ["blur", "change"],
          },
        ],
        checkPwd: [
          {
            required: true,
            message: "请输入分站确认密码",
            trigger: ["blur", "change"],
          },
        ],
        cityId: [
          {
            required: true,
            message: "请选择地区",
            trigger: ["blur", "change"],
          },
        ],
        independent: [
          {
            required: true,
            message: "请选择账号是否独立",
            trigger: ["blur", "change"],
          },
        ],
        name: [
          {
            required: true,
            message: "请输入分站名称",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"],
          },
        ],
        realName: [
          {
            required: true,
            message: "请输入分站超管姓名",
            trigger: ["blur", "change"],
          },
        ],
        status: [
          {
            required: true,
            message: "请选择分站超管状态",
            trigger: ["blur", "change"],
          },
        ],
        routineAppid: [
          {
            required: true,
            message: "请输入AppID(小程序ID)",
            trigger: ["blur", "change"],
          },
        ],
        routineAppsecret: [
          {
            required: true,
            message: "请输入AppSecret(小程序密钥)",
            trigger: ["blur", "change"],
          },
        ],
        payRoutineMchid: [
          {
            required: true,
            message: "请输入商户号",
            trigger: ["blur", "change"],
          },
        ],
        payRoutineCertificatePath: [
          {
            required: true,
            message: "请输入支付证书",
            trigger: ["blur", "change"],
          },
        ],
        payRoutineKey: [
          {
            required: true,
            message: "请输入支付秘钥",
            trigger: ["blur", "change"],
          },
        ],
      },
      cityList: [],
      loading: false,
    };
  },
  created() {
    this.getCityList();
  },
  methods: {
    add() {
      this.isEdit = false;
      this.drawer = true;
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.$refs.ruleForm.clearValidate();
      });
    },
    edit(item) {
      this.currentId = item.id;
      this.getDetail();
      this.isEdit = true;
      this.drawer = true;
    },
    submitForm: Debounce(function () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 数据处理
          let {
            pwd,
            checkPwd,
            routineAppid,
            routineAppsecret,
            payRoutineMchid,
            payRoutineCertificatePath,
            payRoutineKey,
            independent,
          } = this.ruleForm;
          if (pwd !== checkPwd) {
            this.$message.error("两次输入的密码不一致！");
            return;
          }
          let wxProgram = JSON.stringify({
            routine_appid: routineAppid,
            routine_appsecret: routineAppsecret,
          });
          let wxPay = JSON.stringify({
            pay_routine_appid: routineAppid,
            pay_routine_appsecret: routineAppsecret,
            pay_routine_mchid: payRoutineMchid,
            pay_routine_certificate_path: payRoutineCertificatePath,
            pay_routine_key: payRoutineKey,
          });
          let obj = {
            ...this.ruleForm,
            // 微信小程序配置
            wxProgram: independent === 1 ? wxProgram : "",
            // 微信支付配置
            wxPay: independent === 1 ? wxPay : "",
          };
          //   去除多余属性
          delete obj.routineAppid;
          delete obj.routineAppsecret;
          delete obj.payRoutineMchid;
          delete obj.payRoutineCertificatePath;
          delete obj.payRoutineKey;
          if (this.isEdit) {
            putCity({
                id: this.currentId,
                ...obj
            })
              .then((res) => {
                this.$message.success("编辑成功");
                this.drawer = false;
                this.$parent.getCityList();
              })
              .catch((err) => {
                this.$message.error("编辑失败");
              });
          } else {
            postCity(obj)
              .then((res) => {
                this.$message.success("新增成功");
                this.drawer = false;
                this.$parent.getCityList();
              })
              .catch((err) => {
                this.$message.error("新增失败");
              });
          }
        } else {
          return false;
        }
      });
    }),
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    // 获取详情
    async getDetail() {
      this.loading = true;
      const res = await getCityDetail({
        id: this.currentId,
      });
      this.loading = false;
      const {
        account,
        cityId,
        independent,
        name,
        phone,
        realName,
        status,
        wxPay,
        wxProgram,
      } = res;
      this.ruleForm.account = account;
      this.ruleForm.cityId = cityId;
      this.ruleForm.independent = independent;
      this.ruleForm.name = name;
      this.ruleForm.phone = phone;
      this.ruleForm.realName = realName;
      this.ruleForm.status = status;
      if (wxProgram) {
        try {
          let { routine_appid, routine_appsecret } = JSON.parse(wxProgram);
          this.ruleForm.routineAppid = routine_appid;
          this.ruleForm.routineAppsecret = routine_appsecret;
        } catch (error) {
          console.log("微信小程序配置解析出错", wxProgram);
        }
      }
      if (wxPay) {
        try {
          let {
            pay_routine_mchid,
            pay_routine_certificate_path,
            pay_routine_key,
          } = JSON.parse(wxPay);
          this.ruleForm.payRoutineMchid = pay_routine_mchid;
          this.ruleForm.payRoutineCertificatePath =
            pay_routine_certificate_path;
          this.ruleForm.payRoutineKey = pay_routine_key;
        } catch (error) {
          console.log("微信小程序支付配置解析出错", wxPay);
        }
      }
    },
    // 获取城市列表
    async getCityList() {
      const res = await cityListTree();
      this.cityList = res;
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 20px;
  box-sizing: border-box;
  &_label {
    font-size: 18px;
    font-weight: 700;
  }
}
.content {
  height: calc(100vh - 100px);
  overflow-y: auto;
  padding-left: 30px;
  padding-right: 30px;
  padding-bottom: 60px;
  box-sizing: border-box;
}
</style>